/*
    nspire-gamekit - a simple homebrew game framework
    Copyright (C) 2011  Daniel Tang

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <os.h>
#include "textfont.h"
#include "screen.h"
#include "text.h"

static void screenBufferDrawCharacter(uint16_t, uint16_t, unsigned char, char, NGKScreenBuffer*);

NGKScreenBuffer* screenBufferFromString(const char* string) {
    return screenBufferFromStringFormatted(string, 0xF0, 0x00, 2);
}

void screenBufferDrawString(NGKPoint pos, const char* string, char textColor, 
    int characterSpacing, NGKScreenBuffer* screen) {
    uint16_t x = pos.x, y = pos.y;
    
    if (!screen) return;
    
    int strLength = strlen(string);
    int i;
    
    for (i=0; i<strLength; i++) {
        screenBufferDrawCharacter((i*FONT_WIDTH) + characterSpacing + x, y, string[i], textColor, screen);
    }
}

NGKScreenBuffer* screenBufferFromStringFormatted(const char* string, char textColor,
    char backgroundColor, int characterSpacing) {
    
    int imageWidth = (strlen(string)*(characterSpacing + FONT_WIDTH))-characterSpacing;
    
    NGKScreenBuffer* screen = screenBufferAlloc(NGKSizeMake(imageWidth, FONT_HEIGHT));
    if (!screen) return NULL;
    
    screenBufferClear(backgroundColor, screen);
    screenBufferDrawString(NGKPointMake(0,0),string, textColor, characterSpacing, screen);
    
    return screen;
}

static void screenBufferDrawCharacter(uint16_t x, uint16_t y, unsigned char character, char textColor, NGKScreenBuffer* screen) {
    if (!screen) return;
    
    unsigned char *character_data = &(consoleFont[character*FONT_HEIGHT]);
    
    int i, j;
    for (i=0; i<FONT_HEIGHT; i++) {
        for (j=0; j<FONT_WIDTH; j++) {
            if ( ( ( (character_data[i]) >> (FONT_WIDTH-j) ) & 0x1) ) {
                screenBufferSetPixel(NGKPointMake(x+j, y+i), textColor, screen);
            }
        }
    }
}